"use client";

import {
  menuAdd,
  menuDelete,
  menuList,
  menuUpdate,
} from "@/app/actions/menu_action";
import {
  roleAdd,
  roleDelete,
  roleList,
  roleUpdate,
} from "@/app/actions/role_action";
import { MenusItem, geneRateMenuTree } from "@/components/utilUi";
import { useUserStore } from "@/store/userStore";
import { ExclamationCircleOutlined } from "@ant-design/icons";
import { Menu, Role } from "@prisma/client";
import {
  Space,
  Table,
  TableColumnsType,
  Button,
  Modal,
  Form,
  Input,
  Select,
  TreeSelect,
  Tag,
  message,
  Radio,
  Tree,
} from "antd";
import { cloneDeep } from "lodash-es";
import { useEffect, useState } from "react";

export default function RolePage() {
  const [formVal, setFormVal] = useState<Partial<Menu & {
    menus: []
  }>>({});
  const [treeData, setTreeData] = useState<any[]>([]);
  const [form] = Form.useForm();
  const [menus, setMenus] = useState<MenusItem[]>([]);
  const onTreeCheck = (checkedKeys: any, info: any) => {
    // console.log('onCheck', checkedKeys, info);
    form.setFieldValue("menus", checkedKeys);
    setFormVal({
      ...formVal,
      menus: checkedKeys,
    });
  }
  const fetMenu = async () => {
    const menuResult = await menuList();
    if (menuResult.data) {
      const menuTemp = geneRateMenuTree(menuResult.data || [], true);
      const treeList = treeItemList(menuTemp as any);
      setMenus(treeList);

    }
  };
  const columns: TableColumnsType = [
    {
      title: "名称",
      dataIndex: "name",
      key: "name",
    },
    {
      title: "状态",
      dataIndex: "status",
      key: "status",
    },
    {
      title: "创建时间",
      dataIndex: "createdAt",
      key: "createdAt",
    },
    {
      title: "创建人",
      key: "createdAt",
      render: (text, record) => {
        return (
          <Tag color="blue">{record.userInfo?.name}</Tag>
        );
      },
    },
    {
      title: "操作",
      key: "operation",
      render: (record) => (
        <Space size="middle">
          <Button
            size="small"
            type="primary"
            onClick={() => {
              const temp = JSON.parse(record.menuList);
              record.menus = temp ? temp : undefined;
              setFormVal(record);
              form.setFieldsValue(record);
              showModal();
            }}
          >
            编辑
          </Button>
          <Button
            size="small"
            onClick={() => {
              modal.confirm({
                title: "提示",
                icon: <ExclamationCircleOutlined />,
                content: "您确定要删除吗?",
                onOk: async () => {
                  const result = await roleDelete({ id: record.id });

                  if (result.data) {
                    message.success("删除成功");
                    fetRoles();
                  }
                },
                okText: "确认",
                cancelText: "取消",
              });
            }}
            danger
            type="dashed"
          >
            删除
          </Button>
        </Space>
      ),
    },
  ];

  const treeItemList = (
    list: (MenusItem & { id: number; name: string })[]
  ): any => {
    return list.map((item) => {
      return {
        value: item.id,
        title: item.name,
        key: item.id,
        children: item.children
          ? treeItemList(item.children as any)
          : undefined,
      };
    });
  };
  const showModal = () => {
    setIsModalOpen(true);
  };

  const handleCancel = () => {
    setIsModalOpen(false);
  };
  const [roles, setRoles] = useState<Role[]>([]);
  const fetRoles = async () => {
    const roleResult = await roleList();
    if (roleResult.data) {
      setRoles(roleResult.data);
    }
  };
  const [modal, contextHolder] = Modal.useModal();
  const onFinish = async (value: any) => {
    let params = cloneDeep(value);
    params.menuList = JSON.stringify(params.menus);
    let fun = roleAdd;
    if (formVal.id) {
      params.id = formVal.id;
      fun = roleUpdate;
    }

    modal.confirm({
      title: "提示",
      icon: <ExclamationCircleOutlined />,
      content: "您确定要修改吗?",
      onOk: async () => {
        delete params.menus;
        const result = await fun(params);
        // console.log(result);
        if (result.data) {
          message.success("操作成功");
          fetRoles();
          handleCancel();
        }
      },
      okText: "确认",
      cancelText: "取消",
    });
  };

  const [userInfo] = useUserStore((state) => [state.user]);
  const [isModalOpen, setIsModalOpen] = useState(false);

  useEffect(() => {
    fetRoles();
    fetMenu();
  }, []);
  return (
    <div className="h-full">
      {contextHolder}
      <Button
        className="m-2"
        onClick={() => {
          form.setFieldsValue({
            name: "",
            status: 1,
            menus: undefined,
          });
          showModal();
        }}
        type="primary"
      >
        新增角色
      </Button>
      <Table
        rowKey="id"
        columns={columns}
        dataSource={roles}
        pagination={false}
      />
      <Modal
        title="角色编辑"
        footer={null}
        open={isModalOpen}
        width='70%'
        onCancel={handleCancel}
      >
        <Form
          name="nest-messages"
          onFinish={onFinish}
          form={form}
        >
          <Form.Item name="name" label="角色名称" rules={[{ required: true }]}>
            <Input />
          </Form.Item>
          <Form.Item
            name="menus"
            label="角色权限"
            rules={[{ required: true, message: "必须选择权限" }]}
          >
            <Tree
              checkable
              onCheck={onTreeCheck}
              checkedKeys={formVal.menus}
              treeData={menus}>

            </Tree>
            {/* <TreeSelect treeCheckable treeData={menus} /> */}
          </Form.Item>
          <Form.Item
            name="status"
            label="角色状态"
            rules={[{ required: true }]}
          >
            <Radio.Group>
              <Radio value={0}>禁用</Radio>
              <Radio value={1}>启用</Radio>
            </Radio.Group>
          </Form.Item>
          <Form.Item>
            <div className="text-right">
              <Space>
                <Button onClick={handleCancel}>取消</Button>
                <Button type="primary" htmlType="submit">
                  确定
                </Button>
              </Space>
            </div>
          </Form.Item>
        </Form>
      </Modal>
      {/* <XTable update={update} deleteItem={deleteItem} getList={getList} columns={columns}></XTable> */}
    </div>
  );
}
